package com.multiplepb.mapper;

import com.multiplepb.entity.CommonInfo;
import com.multiplepb.utils.SQLiteUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 */
@Component
public class CommonInfoDao {
    Log log = LogFactory.getLog(CommonInfoDao.class);
    public void insertOrReplace(String value, Integer type) throws Exception {
        String sql = "INSERT OR REPLACE INTO common_info(common_type,common_value)" +
                "VALUES(?,?)";
        PreparedStatement statement = SQLiteUtils.getConnect().prepareStatement(sql);
        try {
            statement.setInt(1, type);
            statement.setString(2, value);
            statement.executeUpdate();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new Exception(e);
        } finally {
            statement.close();
        }
    }
    public void insert(CommonInfo commonInfo) throws Exception {
        String sql = "INSERT INTO common_info(common_type,common_value)" +
                "VALUES(?,?)";
        PreparedStatement statement = SQLiteUtils.getConnect().prepareStatement(sql);
        try {
            statement.setInt(1, commonInfo.getCommonType());
            statement.setString(2, commonInfo.getCommonValue());
            statement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new Exception(e);
        } finally {
            statement.close();
        }
    }

    public CommonInfo selectByType(Integer type) throws Exception {
        String sql = "SELECT id, common_type, common_value FROM common_info WHERE common_type = " + type;
        Statement statement = SQLiteUtils.getConnect().createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        try {
            if (resultSet.next()) {
                CommonInfo commonInfo = new CommonInfo();
                commonInfo.setId(resultSet.getInt("id"));
                commonInfo.setCommonType(resultSet.getInt("common_type"));
                commonInfo.setCommonValue(resultSet.getString("common_value"));
                return commonInfo;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new Exception(e);
        } finally {
            resultSet.close();
            statement.close();
        }

        return null;
    }
}
